<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
      <el-row :gutter="20">
        <!-- 输入框 -->
        <el-col :span="8">
          <el-input placeholder="请输入内容" clearable v-model="queryInfo.query" @clear="getGoodsList">
            <el-button slot="append" icon="el-icon-search" @click="getGoodsList" class="qbtn"></el-button>
          </el-input>
        </el-col>
        <!-- 添加按钮 -->
        <el-col :span="4">
          <el-button type="primary" @click="goAddpage">添加商品</el-button>
        </el-col>
      </el-row>

      <!-- 商品表格区域 -->
      <el-table :data="goodsList" border stripe>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column prop="goods_name" label="商品名称"> </el-table-column>
        <el-table-column prop="goods_price" label="商品价格(元)" width="70px">
        </el-table-column>
        <el-table-column prop="goods_weight" label="商品重量(克)" width="70px"> </el-table-column>
        <el-table-column prop="goods_number" label="商品数量(个)" width="70px"> </el-table-column>
        <el-table-column label="创建时间" width="140px">
          <template slot-scope="scope">
            {{scope.row.add_time | dataFormat}}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="130px">
          <template slot-scope="scope">
            <!-- 编辑按钮 -->
            <el-button type="primary" size="mini" icon="el-icon-edit" @click="showEditDialog(scope.row.goods_id)"></el-button>
            <!-- 删除按钮 -->
            <el-button type="danger" size="mini" icon="el-icon-delete" @click="removeGood(scope.row.goods_id)"></el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
       <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryInfo.pagenum"
          :page-sizes="[5, 10, 15, 20]"
          :page-size="queryInfo.pagesize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          background
          >
       </el-pagination>
    </el-card>

     <!-- 编辑对话框 -->
    <el-dialog
      title="编辑商品信息"
      :visible.sync="eidtDialogVisible"
      width="50%"
      @close="editDialogClosed">
      <el-form 
      :model="editForm" 
      :rules="editFormRules" 
      ref="editFormRef" 
      label-width="80px">
        <el-form-item label="商品名称" prop="goods_name">
          <el-input v-model="editForm.goods_name"></el-input>
        </el-form-item>
        <el-form-item label="商品价格" prop="goods_price">
          <el-input v-model="editForm.goods_price" type="number"></el-input>
        </el-form-item>
        <el-form-item label="商品重量" prop="goods_weight">
          <el-input v-model="editForm.goods_weight" type="number"></el-input>
        </el-form-item>
        <el-form-item label="商品数量" prop="goods_number">
          <el-input v-model="editForm.goods_number" type="number"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="eidtDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editFormSubmit">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'List',
  data() {
    // 自定义验证规则
    var checkNumber = (rule, value, cb) => {
      if (value > 0) {
        return cb()
      }
      cb(new Error('此项必须大于零'))
    }
    return {
      // 获取商品数据的请求参数
      queryInfo: {
        query: '',
        pagenum: 1,
        pagesize: 10,
      },
      // 商品列表数据
      goodsList: [],
      // 商品总数据条数
      total: 0,
      // 控制编辑对话框的显示与隐藏
      eidtDialogVisible:false,
      // 编辑表单数据对象
      editForm:{
        // goods_name:'',
        // goods_price:'',
        // goods_weight:'',
        // goods_number:''
      },
      // 编辑表单验证规则对象
      editFormRules:{
        goods_name:[
          { required: true, message: '请输入商品名称', trigger: 'blur' },
        ],
        goods_price:[
          { required: true,validator:checkNumber, trigger: 'blur' },
        ],
        goods_weight:[
          { required: true,validator:checkNumber, trigger: 'blur' },
        ],
        goods_number:[
          { required: true,validator:checkNumber, trigger: 'blur' },
        ]
      }
    }
  },
  created() {
    // 加载商品列表数据根据分页
    this.getGoodsList()
  },
  methods: {
    // 加载商品列表数据根据分页
    async getGoodsList() {
      const { data: res } = await this.$http.get('goods', {
        params: this.queryInfo,
      })
      if (res.meta.status !== 200) {
        return this.$message.error(
          '加载商品列表数据失败，状态码为：' + res.meta.status
        )
      }
      this.goodsList = res.data.goods
      this.total = res.data.total
    },
    // 改变表格展现数据的数量
    handleSizeChange(newSize){
      this.queryInfo.pagesize = newSize
      this.getGoodsList()
    },
    // 分页变换
    handleCurrentChange(newPage){
      this.queryInfo.pagenum = newPage
      this.getGoodsList()
    },
    // 删除商品信息
    async removeGood(id){
      const confirmResult = await this.$confirm('此操作将永久删除该商品数据, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err=>err)
        if(confirmResult !== 'confirm'){
          return this.$message.info('已取消删除！')
        }
        const {data:res} = await this.$http.delete('goods/'+id)
        if(res.meta.status !== 200){
          return this.$message.error('删除商品信息失败，状态码为：'+res.meta.status)
        }
        // 刷新数据列表
        this.getGoodsList()
        // 弹框提示
        this.$message.success('删除商品信息成功！')
    },
    // 跳转到添加商品组件
    goAddpage(){
      this.$router.push('/goods/add')
    },
    // 展示编辑商品参数对话框
    async showEditDialog(id){
      const {data:res} = await this.$http.get('goods/'+id)
      if(res.meta.status !== 200){
        return this.$message.error('加载商品列表数据失败，状态码为：'+res.meta.status)
      }
      this.editForm = res.data
      this.eidtDialogVisible = true
    },
    // 监听对话框的关闭事件
    editDialogClosed(){
      this.$refs.editFormRef.clearValidate()
    },
    // 编辑表单提交
    editFormSubmit(){
      this.$refs.editFormRef.validate(async valid=>{
        if(!valid){
          return this.$message.error('错误的格式，修改商品信息失败！')
        }
        const {data:res} = await this.$http.put(`goods/${this.editForm.goods_id}`,this.editForm)
        if(res.meta.status === 400){
          return this.$message.error('该商品名称已被注册，修改商品信息失败！')
        }
        if(res.meta.status !== 200){
          return this.$message.error('修改商品信息失败，状态码为：'+res.meta.status)
        }
        // 关闭对话框
        this.eidtDialogVisible = false
        // 刷新数据列表
        this.getGoodsList()
        // 弹框提示
        this.$message.success('修改商品信息成功！')
      })

    }
  },
}
</script>

<style lang="less" scoped>
.qbtn:hover{
  background-color: #e7e9ec;
}
</style>